package com.example.shuiyin.service.impl;

import com.example.shuiyin.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.TemplateEngine;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    @Value("${spring.mail.from:noreply@example.com}")
    private String fromEmail;

    @Value("${spring.mail.personal:水印系统}")
    private String fromName;

    @Value("${password.reset.url:http://localhost:8080/reset-password}")
    private String resetPasswordUrl;
    
    @Value("${password.reset.template:email/reset-password}")
    private String resetPasswordTemplate;

    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            log.info("发送简单邮件到 {}, 主题: {}", to, subject);
        } catch (Exception e) {
            log.error("发送简单邮件失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送邮件失败: " + e.getMessage());
        }
    }

    @Override
    public void sendHtmlEmail(String to, String subject, String htmlContent) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail, fromName);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            mailSender.send(message);
            log.info("发送HTML邮件到 {}, 主题: {}", to, subject);
        } catch (Exception e) {
            log.error("发送HTML邮件失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送邮件失败: " + e.getMessage());
        }
    }

    @Override
    public void sendPasswordResetEmail(String to, String resetToken, String username) {
        try {
            // 生成重置链接
            String resetLink = resetPasswordUrl + "?token=" + resetToken;
            
            // 准备Thymeleaf上下文
            Context context = new Context();
            context.setVariable("username", username);
            context.setVariable("resetUrl", resetLink);
            context.setVariable("expireHours", "24");
            
            // 使用模板引擎处理模板
            String htmlContent = templateEngine.process(resetPasswordTemplate, context);
            
            // 如果模板处理失败，使用备用方法
            if (htmlContent == null || htmlContent.trim().isEmpty()) {
                log.warn("模板引擎处理失败，使用备用方法");
                htmlContent = processResetEmailFallback(username, resetLink);
            }

            sendHtmlEmail(to, "【水印系统】密码重置", htmlContent);
            log.info("发送密码重置邮件到 {}, 重置链接: {}", to, resetLink);
        } catch (Exception e) {
            log.error("发送密码重置邮件失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送密码重置邮件失败: " + e.getMessage());
        }
    }
    
    /**
     * 备用的模板处理方法
     */
    private String processResetEmailFallback(String username, String resetLink) throws IOException {
        try {
            // 尝试从classpath加载模板
            ClassPathResource resource = new ClassPathResource("templates/" + resetPasswordTemplate + ".html");
            String template = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            
            // 替换模板中的变量
            return template
                    .replace("${username}", username)
                    .replace("${resetUrl}", resetLink)
                    .replace("${expireHours}", "24");
        } catch (IOException e) {
            log.warn("未找到邮件模板 {}, 使用默认模板", resetPasswordTemplate);
            return getDefaultPasswordResetTemplate()
                    .replace("{{username}}", username)
                    .replace("{{resetLink}}", resetLink)
                    .replace("{{expireHours}}", "24");
        }
    }
    
    /**
     * 获取默认密码重置邮件模板
     */
    private String getDefaultPasswordResetTemplate() {
        return "<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>密码重置</title>\n" +
                "    <style>\n" +
                "        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }\n" +
                "        .container { max-width: 600px; margin: 0 auto; padding: 20px; }\n" +
                "        .header { background-color: #4A90E2; color: white; padding: 10px 20px; }\n" +
                "        .content { padding: 20px; border: 1px solid #ddd; }\n" +
                "        .button { display: inline-block; padding: 10px 20px; background-color: #4A90E2; color: white; text-decoration: none; border-radius: 4px; }\n" +
                "        .footer { margin-top: 20px; font-size: 12px; color: #888; }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"container\">\n" +
                "        <div class=\"header\">\n" +
                "            <h2>密码重置</h2>\n" +
                "        </div>\n" +
                "        <div class=\"content\">\n" +
                "            <p>尊敬的 {{username}},</p>\n" +
                "            <p>我们收到了您的密码重置请求。请点击下面的链接重置您的密码：</p>\n" +
                "            <p>\n" +
                "                <a class=\"button\" href=\"{{resetLink}}\">重置密码</a>\n" +
                "            </p>\n" +
                "            <p>或者，您可以复制以下链接到浏览器地址栏：</p>\n" +
                "            <p><a href=\"{{resetLink}}\">{{resetLink}}</a></p>\n" +
                "            <p>该链接将在 {{expireHours}} 小时后过期。</p>\n" +
                "            <p>如果您没有请求重置密码，请忽略此邮件。</p>\n" +
                "        </div>\n" +
                "        <div class=\"footer\">\n" +
                "            <p>此邮件由系统自动发送，请勿回复。</p>\n" +
                "            <p>&copy; 2023 水印系统 版权所有</p>\n" +
                "        </div>\n" +
                "    </div>\n" +
                "</body>\n" +
                "</html>";
    }
} 